package com.yssystem.controller;

import com.yssystem.domain.dto.UserDto;
import com.yssystem.domain.vo.R;
import com.yssystem.service.SysLoginService;
import com.yssystem.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private  RedisTemplate<String,String> redisTemplate;
    @PostMapping
    public R login(@RequestBody UserDto userDto) {
        UserDto name = loginService.getUser(userDto.getUsername());
        //账号不存在
        if (name == null) {
            return new R(false,"用户不存在",401);
        }
        String password = DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes());
        //判断密码是否正确
        if (password.equals(name.getPassword())){
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", name.getId());
            claims.put("username", userDto.getUsername());
            String token = JwtUtil.genToken(claims);
            redisTemplate.opsForValue().set(userDto.getUsername(), token,10, TimeUnit.SECONDS);
//            redisTemplate.opsForValue().set(username, token,12, TimeUnit.HOURS);

            return new R(true,"登录成功",token);
        }
        return new R(false,"密码错误",401);

    }
}
